package com.tiancheng.trade.settlement.service.settlement.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.commom.core.utils.DateTimeUtil;
import com.tiancheng.trade.settlement.mapper.settlement.PaymentBankDataCmbMapper;
import com.tiancheng.trade.settlement.mapper.settlement.PaymentBillComparisonDetailMapper;
import com.tiancheng.trade.settlement.mapper.settlement.PaymentBillComparisonMapper;
import com.tiancheng.trade.settlement.model.settlement.PaymentBankDataCmb;
import com.tiancheng.trade.settlement.model.settlement.PaymentBillComparison;
import com.tiancheng.trade.settlement.model.settlement.PaymentBillComparisonDetail;
import com.tiancheng.trade.settlement.service.settlement.IComparisonFlowService;
import com.tiancheng.trade.settlement.vo.settlement.admin.ComparisonFlowVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ComparisonFlowService implements IComparisonFlowService {
    @Autowired
    private PaymentBillComparisonMapper mapper;
    @Autowired
    private PaymentBankDataCmbService paymentBankDataCmbService;
    @Autowired
    private PaymentBankDataCmbMapper paymentBankDataCmbMapper;
    @Autowired
    private PaymentBillComparisonDetailMapper detailMapper;

    @Transactional
    @Override
    public PaymentBillComparison queryComparisonInfo(String date) {
        PaymentBillComparison comparison = getPaymentBillComparison(date);
        if (comparison == null) {
            log.info("queryComparisonInfo begin");
            Map<String, Object> dataMap = new HashMap<>();
            List<PaymentBankDataCmb> serverDatas = paymentBankDataCmbService.getPayCsvDataList(DateTimeUtil.formatDate(date, "yyyy-MM-dd"));
            log.info("queryComparisonInfo PaymentBankDataCmb:{}", serverDatas);
            //List<PaymentBankDataCmb> serverDatas = paymentBankDataCmbService.getPaymentBankDataCmb("C:\\Users\\dell\\Desktop\\CMB_20240613.csv");
            if (CollectionUtils.isEmpty(serverDatas)) {
//                comparison = new PaymentBillComparison();
//                return comparison;
                //新需求，如果银行侧未获取到流水文件，条数设置成0
                serverDatas = new ArrayList<>();
            }
            List<String> systemDatas = paymentBankDataCmbMapper.findByStatementDate(date);
            //差异条数集合
            List<PaymentBillComparisonDetail> saveDetailData = new ArrayList<PaymentBillComparisonDetail>();
            if (CollectionUtils.isEmpty(systemDatas)) {
                systemDatas = new ArrayList<>();
                for (PaymentBankDataCmb cmb : serverDatas) {
                    PaymentBillComparisonDetail cmp = new PaymentBillComparisonDetail();
                    cmp.setPayChannelOrderid(cmb.getBankSerialNumber());
                    saveDetailData.add(cmp);
                }
            } else {
                for (String cmb : systemDatas) {
                    dataMap.put(cmb, cmb);
                }
                for (PaymentBankDataCmb cmb : serverDatas) {
                    if (!dataMap.containsKey(cmb.getBankSerialNumber())) {
                        PaymentBillComparisonDetail cmp = new PaymentBillComparisonDetail();
                        cmp.setPayChannelOrderid(cmb.getBankSerialNumber());
                        saveDetailData.add(cmp);
                    }
                }
            }
            comparison = new PaymentBillComparison();
            if (!saveDetailData.isEmpty()) {
                comparison.setStatementDate(date);
                comparison.setComparisonStatus("wait");
                if (CollectionUtils.isNotEmpty(systemDatas)) {
                    comparison.setErrorCount(serverDatas.size() - systemDatas.size());
                    comparison.setSystemCount(systemDatas.size());
                }
                comparison.setServerCount(serverDatas.size());
                mapper.insert(comparison);
                Long comparisonId = comparison.getId();
                saveDetailData.forEach(detail -> {
                    detail.setComparisonId(comparisonId);
                });
                detailMapper.saveBatch(saveDetailData);
                Integer subOrderCount = detailMapper.querySubOrderCount(comparisonId);
                comparison.setSubOrderCount(subOrderCount);
                mapper.updateById(comparison);
                return comparison;
            } else {
                comparison.setErrorCount(0);
                comparison.setServerCount(serverDatas.size());
                if (CollectionUtils.isNotEmpty(systemDatas)) {
                    comparison.setSystemCount(systemDatas.size());
                }
                comparison.setSubOrderCount(0);
                return comparison;
            }
        }
        return comparison;
    }

    @Override
    public Result proccess(ComparisonFlowVO vo) {
        PaymentBillComparison comparison = getPaymentBillComparison(vo.getDate());
        if (comparison == null) {
            log.info("proccess 没有查询到需要对比的数据");
            return Result.fail("请先比对数据");
        } else if ("fail".equals(comparison.getComparisonStatus())
                || "wait".equals(comparison.getComparisonStatus())) {
            int count = detailMapper.updateOrderFinish(comparison.getId());
            log.info("更新的流水结果数据：{}", count);
            vo.setComparisonId(comparison.getId());
            int number = detailMapper.updateSubOrder(vo);
            log.info("更新的子订单数据：{}", number);
            comparison.setComparisonStatus("success");
            comparison.setLastUpdDt(LocalDateTime.now());
            mapper.updateById(comparison);
            return Result.success();
        } else {
            return Result.fail("当前日期对应的子订单数据已备注，请勿重复操作");
        }
    }


    private PaymentBillComparison getPaymentBillComparison(String date) {
        QueryWrapper<PaymentBillComparison> conditions = new QueryWrapper<>();
        conditions.eq("statement_date", date);
        PaymentBillComparison comparison = mapper.selectOne(conditions);
        return comparison;
    }

}
